<template>
  <div class="big-upload">
    <el-upload
      :drag="drag"
      :accept="accept"
      :multiple="multiple"
      :disabled="disabled"
      :auto-upload="false"
      :on-change="handleUploadChange"
      ref="elUploaderRef"
      :show-file-list="false"
    >
      <slot></slot>
    </el-upload>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue";
import _ from "lodash";
import { ElMessage } from "element-plus";
const { VITE_PUBLIC_PATH } = import.meta.env;
const props = defineProps({
  // 上传类型
  accept: {
    type: String,
    default: ".jpg,.png,.jpeg",
  },
  // 是否拖拽 上传
  drag: {
    type: Boolean,
    default: true,
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否支持多选文件
  multiple: {
    type: Boolean,
    default: false,
  },
  // 文件大小限制
  fileSize: {
    type: Number,
    default: 1024 * 1024 * 1024,
  },
  // 分片大小
  chunkSize: {
    type: Number,
    default: 5242880,
  },
  // 是否开启分片
  chunked: {
    type: Boolean,
    default: true,
  },
});

const elUploaderRef = ref(null);

const emit = defineEmits(["onChange"]);
const handleUploadChange = (file) => {

  // 禁用ElUpload组件的上传，只是使用其UI，所以该事件触发仅有可能是添加文件
  //  判断文件大小
  if (file.raw.size > props.fileSize) {
    elUploaderRef.value.handleRemove(file);
    ElMessage.error("上传文件不能大于" + props.fileSize / 1024 / 1024 + "MB");
    return;
  }
  //判断文件类型
  if (props.accept) {
    const type = file.name.substring(file.name.lastIndexOf(".") + 1);
    const ddd = props.accept.split(",").filter((item) => item === "." + type);
    if (ddd.length === 0) {
      elUploaderRef.value.handleRemove(file);
      ElMessage.warning(`上传文件只能是${props.accept}格式!`);
      return;
    }
  }
  emit("onChange", file);
};

defineExpose({});
</script>

<style scoped lang="scss"></style>
